package pgsql

import (
	"fmt"
	"os"

	"dragonfly/common/config"
	"dragonfly/common/log"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"

	"github.com/rs/zerolog"
)

type DataSource struct {
	host     string
	port     int
	user     string
	password string
	database string
	schema   string
	sslMode  string
}

type Client struct {
	db     *sqlx.DB
	logger *zerolog.Logger
	ds     *DataSource
}

func NewClient(cfg *config.Config, ds *DataSource) *Client {
	dsn := fmt.Sprintf("host=%v port=%v user=%v dbname=%v password='%v' sslmode=%v connect_timeout=10",
		ds.host, ds.port, ds.user, ds.database, ds.password, ds.sslMode)
	logger := log.NewLogger(&cfg.LogSettings)
	db, err := sqlx.Open("postgres", dsn)
	logger.Info().Msgf("connecting pgsql %s", dsn)
	if err != nil {
		logger.Error().Msg("connect pgsql failed")
		os.Exit(1)
	}

	return &Client{db, logger, ds}
}
